package com.teamone.etl.util;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.*;

/**
 * @Description 线程池工具类
 * @Author WangZhuoRan
 * @Date 2021-01-11 21:31
 */
public class ThreadPool {
    /**
     线程池本池
     */
    private ThreadPoolExecutor executor;
    /**
     核心线程池数量
     */
    private int corePoolSize = 60;
    /**
     最大线程池数量
     */
    private int maxPoolSize = 60;
    /**
     空闲线程存活时间
     */
    private long keepAliveTime = 3L;
    /**
     时间单位
     */
    private TimeUnit timeUnit = TimeUnit.MINUTES;
    /**
     线程池名字
     */
    private String poolName = "ThreadPool-Thread-%d";

    public ThreadPool (){
        init();
    }

    public ThreadPool (int corePoolSize, int maxPoolSize){
        this.corePoolSize = corePoolSize;
        this.maxPoolSize = maxPoolSize;
        init();
    }

    public ThreadPool (long keepAliveTime, TimeUnit timeUnit){
        this.keepAliveTime = keepAliveTime;
        this.timeUnit = timeUnit;
        init();
    }

    public ThreadPool (int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit){
        this.corePoolSize = corePoolSize;
        this.maxPoolSize = maxPoolSize;
        this.keepAliveTime = keepAliveTime;
        this.timeUnit = timeUnit;
        init();
    }

    public ThreadPool (int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit, String poolName){
        this.corePoolSize = corePoolSize;
        this.maxPoolSize = maxPoolSize;
        this.keepAliveTime = keepAliveTime;
        this.timeUnit = timeUnit;
        this.poolName = poolName;
        init();
    }

    private void init(){
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setThreadFactory(Executors.defaultThreadFactory())
                .setNameFormat(poolName)
                .build();
        executor = new ThreadPoolExecutor(corePoolSize,
                maxPoolSize,
                keepAliveTime,
                timeUnit,
                new LinkedBlockingDeque<>(40),
                namedThreadFactory);
    }

    public void execute(Runnable task){
        executor.execute(task);
    }

    public void shutdown(){
        executor.shutdown();
    }

    public void shutdownNow(){
        executor.shutdownNow();
    }

    public boolean isShutdown (){
        return executor.isShutdown();
    }

}